package com.fly.openapi.service;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.fly.openapi.entity.AuthToken;

/**
 * AutoTokenService
 */
@Service
public class AutoTokenService
{
    Map<String, AuthToken> tokens = new ConcurrentHashMap<>();
    
    /**
     * 获取用户鉴权令牌
     */
    public AuthToken getToken(String user)
    {
        String userId = DigestUtils.md5DigestAsHex(user.getBytes(StandardCharsets.UTF_8));
        if (StringUtils.isBlank(userId))
        {
            throw new RuntimeException("用户不存在");
        }
        // 优先返回缓存token
        Date now = new Date();
        if (tokens.containsKey(user))
        {
            AuthToken saved = tokens.get(user);
            if (now.before(saved.getTokenTime()))
            {
                return saved;
            }
        }
        
        // 新建token
        String token = UUID.randomUUID().toString();
        Date tokenTime = DateUtils.addHours(now, 8);
        AuthToken authToken = new AuthToken().setUserId(userId).setUserName(user).setToken(token).setTokenTime(tokenTime);
        tokens.put(user, authToken);
        return authToken;
    }
    
    /**
     * 判断用户token是否有效
     */
    public boolean isPass(String user, String token)
    {
        return StringUtils.equals(getToken(user).getToken(), token);
    }
}